package com.hevery.blog.common.exception;

import com.hevery.blog.common.annotation.ExceptionStatus;
import com.hevery.blog.common.security.CustomSecurityException;
import com.hevery.blog.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 全局异常处理
 * @author: hongyu.zhang
 * @create: 2018-04-03
 **/
@Slf4j
@Component
@ControllerAdvice
public class CustomExceptionHandler {

    @Resource
    private MappingJackson2JsonView mappingJackson2JsonView;

    @ExceptionHandler(Exception.class)
    public ModelAndView customException(HttpServletRequest request, HttpServletResponse response, Exception e){
        log.error("custom exception:{}",e.getClass());
        ModelAndView mv = new ModelAndView();
        if(WebUtil.isAjaxRequest(request)){
            mv.setView(mappingJackson2JsonView);

        }else {
            mv.setViewName("50x");
        }
        ExceptionStatus exceptionStatus = AnnotationUtils.findAnnotation(e.getClass(),ExceptionStatus.class);
        if(exceptionStatus != null){
            mv.addObject("status",exceptionStatus.code());
            mv.addObject("desc",exceptionStatus.reason());
        }else {
            mv.addObject("status",-1);
            mv.addObject("desc",e.getMessage());
        }
        return mv;
    }
}
